package sit.engreal.leetcode.problems1000;

import org.junit.jupiter.api.Assertions;

/**
 * <a herf="https://leetcode.cn/problems/squares-of-a-sorted-array/">977. 有序数组的平方</a>
 */
public class LeetCode997 {
    public static class Solution {
        public int[] sortedSquares(int[] nums) {
            int[] array = new int[nums.length];
            int k = array.length - 1;
            int i = 0;
            int j = nums.length - 1;

            while (i < j) {
                int a = nums[i] * nums[i];
                int b = nums[j] * nums[j];
                if (a > b) {
                    array[k] = a;
                    i++;
                } else {
                    array[k] = b;
                    j--;
                }
                k--;
            }
            array[k] = nums[i] * nums[i];
            return array;
        }
    }

    public static void main(String[] args) {
        final Solution solution = new Solution();

        Assertions.assertArrayEquals(
                new int[]{0, 1, 9, 16, 100},
                solution.sortedSquares(new int[]{-4, -1, 0, 3, 10})
        );


        Assertions.assertArrayEquals(
                new int[]{4, 9, 9, 49, 121},
                solution.sortedSquares(new int[]{-7, -3, 2, 3, 11})
        );
    }
}

